package com.shop.shoppingmall.service.impl;

import com.shop.shoppingmall.dao.*;
import com.shop.shoppingmall.entity.*;
import com.shop.shoppingmall.service.ShIntegralService;
import com.shop.shoppingmall.service.ShProportionService;
import com.shop.shoppingmall.service.ShWalletService;
import com.shop.shoppingmall.util.UUIDGenerator;
import com.shop.shoppingmall.util.api.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.List;

/**
 * 比例(ShProportion)表服务实现类
 *
 * @author makejava
 * @since 2020-09-11 08:58:06
 */
@Service("shProportionService")
@Slf4j
@Transactional
public class  ShProportionServiceImpl implements ShProportionService {
    @Resource
    private ShProportionDao shProportionDao;


    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Result queryById(String id) {
        ShProportion shProportion= shProportionDao.queryById(id);
        if(shProportion !=null){
            //下面将结果转化成百分比
            NumberFormat percent = NumberFormat.getPercentInstance();
            shProportion.setPercent(percent.format(shProportion.getProportion().doubleValue()));
            return Result.ok(shProportion);
        }else{
            return Result.error("未查询到数据");
        }

    }

    /**
     * 新增数据
     *
     * @param shProportion 实例对象
     * @return 实例对象
     */
    @Override
    public Result insert(ShProportion shProportion) {
        shProportion.setId(UUIDGenerator.generate());
        shProportionDao.insert(shProportion);
        return Result.ok("添加成功");
    }

    /**
     * 修改数据
     *
     * @param shProportion 实例对象
     * @return 实例对象
     */
    @Override
    public Result update(ShProportion shProportion) {
        shProportion.setProportion(new BigDecimal(shProportion.getPercent()).divide(new BigDecimal(100)));
        shProportionDao.update(shProportion);
        return Result.ok("修改成功");
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(String id) {
        return this.shProportionDao.deleteById(id) > 0;
    }


    @Override
    public Result queryAll() {
        List<ShProportion> shProportionList = shProportionDao.queryAll();
        for(ShProportion shProportion : shProportionList){
//下面将结果转化成百分比
//            NumberFormat percent = NumberFormat.getPercentInstance();
//            shProportion.setPercent(percent.format(shProportion.getProportion().doubleValue()));


            BigDecimal bd = shProportion.getProportion().multiply(new BigDecimal(100));
            shProportion.setPercent(  bd.setScale(1,RoundingMode.HALF_UP).toPlainString()+"%");



        }
        return Result.ok(shProportionList);
    }

}
